﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace Agnes.MyDocsLib
{
    /// <summary>
    /// DocsLibSmartTree.xaml 的交互逻辑
    /// </summary>
    public partial class DocsLibSmartTreeView : UserControl
    {
        /// <summary>
        /// 构造函数
        /// </summary>
        public DocsLibSmartTreeView()
        {
            InitializeComponent();
        }

        private void StackPanel_PreviewMouseDown(object sender, MouseButtonEventArgs e)
        {           
            StackPanel tb = sender as StackPanel;
            if (tvMyDocsTree.SelectedItem != null)
            {
                var selNode = tvMyDocsTree.SelectedItem;

                if (selNode is IArticleNode)
                {
                    ArticleManager.Instance.SelectedNode = (IArticleNode) selNode;
                }

                if (e.ClickCount == 2 && e.ChangedButton == MouseButton.Left)
                {
                    TreeViewItem treeViewItem 
                        = VisualUpwardSearch<TreeViewItem>(e.OriginalSource as DependencyObject) as TreeViewItem;
                    if (treeViewItem != null)
                    {
                        treeViewItem.IsExpanded = !treeViewItem.IsExpanded;
                    }
                }
            }
        }

        private void TreeViewItem_PreviewMouseRightButtonDown(object sender, MouseButtonEventArgs e)
        {
            var treeViewItem = VisualUpwardSearch<TreeViewItem>(e.OriginalSource as DependencyObject) as TreeViewItem;
           
            if (treeViewItem != null)
            {
                treeViewItem.IsSelected = true;
                treeViewItem.Focus();
                ArticleManager.Instance.SelectedNode = treeViewItem.DataContext as IArticleNode;
                e.Handled = true;
            }
        }

        static DependencyObject VisualUpwardSearch<T>(DependencyObject source)
        {
            while (source != null && source.GetType() != typeof(T))
            {
                source = VisualTreeHelper.GetParent(source);
            }

            return source;
        } 





    }
}
